﻿using System;
using Deferred.Library.Scene.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace Deferred.Library.Scene.Visual
{
    class DrawableObjectVisual : GraphicalComponent
    {
        private DualContentManager content;
        private DeferredModel model;

        protected override bool LoadContentUponCreation { get { return false; } }

        public DrawableObject DrawableObject { get; private set; }

        public Matrix World
        {
            get
            {
                return Matrix.CreateScale(DrawableObject.Scale)
                       * Matrix.CreateFromQuaternion(DrawableObject.Rotation)
                       * Matrix.CreateTranslation(DrawableObject.Position);
            }
        }
        public DeferredModel Model
        {
            get
            {
                return model;
            }
            private set
            {
                model = value;
                model.LoadContent(content);
            }
        }

        public DrawableObjectVisual(DeferredBase deferredBase, DrawableObject drawableObject)
            : base(deferredBase.DeviceService)
        {
            content = deferredBase.Content;
            this.DrawableObject = drawableObject;
            drawableObject.OnModelNameChanged += new System.EventHandler(delegate(object s, EventArgs e) { LoadContent(); });

            if (GraphicsDevice != null) LoadContent();
        }

        protected override void LoadContent()
        {
            LoadModel();
        }

        private void LoadModel()
        {
            if (!string.IsNullOrEmpty(DrawableObject.ModelName))
            {
                try
                {
                    Model = content.ExternalContent.Load<DeferredModel>(DrawableObject.ModelName);
                }
                catch (ContentLoadException)
                {
                    LoadDefaultModel();
                }
            }
            else
            {
                LoadDefaultModel();
            }
        }

        private void LoadDefaultModel()
        {
            string name = typeof(DeferredModelReader).AssemblyQualifiedName;
            Model = content.InternalContent.Load<DeferredModel>("defaultModel");
        }
    }
}
